package com.kgc.crowd.distributioncrowdwebui.controller;

import com.kgc.crowd.distributioncrowdcommon.api.MemberManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.ProjectManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.MemberLaunchInfoPO;
import com.kgc.crowd.distributioncrowdcommon.pojo.ResultEntity;
import com.kgc.crowd.distributioncrowdcommon.pojo.TypePO;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crowd.distributioncrowdcommon.util.UploadUtil;
import com.kgc.crowd.distributioncrowdcommon.vo.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/project/manager")
@Controller
public class ProjectController {
    @Value("${endpint}")
    private String endpint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @Value("${headPictureFolderName}")
    private String headPictureFolderName;


    @Value("${detailPictureFolderName}")
    private String detailPictureFolderName;

    @Value("${bucketName}")
    private String bucketName;
    @Value("${domain}")
    private String domain;

    @Value("${returnFolderName}")
    private String returnFolderName;


    @Resource
    ProjectManagerRemoteService projectManagerRemoteService;
    @Resource
    MemberManagerRemoteService memberManagerRemoteService;

    @RequestMapping("/start")
    public String toStart(){
        return "start";
    }

    @RequestMapping("/agree/protocol")
    public String agreeProtocol(HttpSession session, Model model){
        //获取登录状态
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute==null){
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)attribute;
        String token = memberSignSuccessVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> listResultEntity = projectManagerRemoteService.selectAllType();
        model.addAttribute(CrowdConstant.ATTT_NAME_TYPYPO_LIST,listResultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> allTag = projectManagerRemoteService.selectAllTag();
        model.addAttribute(CrowdConstant.ATTT_NAME_TAG_LIST,allTag.getData());
        //回显发起人信息
        ResultEntity<MemberLaunchInfoPO> retrievelaunchinfotoken = memberManagerRemoteService.retrievelaunchinfotoken(token);
        model.addAttribute(CrowdConstant.ATTR_NAME_INFO_TOKEN,retrievelaunchinfotoken.getData());
        //初始化projectVO
        ResultEntity<ProjectVO> projectVOResultEntity = projectManagerRemoteService.initCreation(token);
        if(projectVOResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,projectVOResultEntity.getMessage());
            return "redirect:/project/manager/start";
        }
        //把projectVO存入session
        session.setAttribute(CrowdConstant.ATTT_NAME_INITER_PROJECT,projectVOResultEntity.getData());
        return "start-step-1.html";
    }

    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> uploadHeadPicture(MultipartFile headerPicture,HttpSession session) throws IOException{
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(obj==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken = memberSignSuccessVO.getToken();
        Object obj2 = session.getAttribute(CrowdConstant.ATTT_NAME_INITER_PROJECT);
        if(obj2==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITER_PROJECT);
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken = projectVO.getProjectTempToken();

        if(headerPicture==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        String originalFilename = headerPicture.getOriginalFilename();
        String fileName = UploadUtil.generateFileName(originalFilename);
        InputStream inputStream = headerPicture.getInputStream();
        UploadUtil.uploadSingleFile(endpint,accessKeyId,accessKeySecret,fileName,headPictureFolderName,bucketName,inputStream);
        String headPicturePath = domain+"/"+headPictureFolderName+"/"+fileName;

        ResultEntity<String> ResultEntity = projectManagerRemoteService.saveHeadPicturePath(memberSignToken, projectTempToken, headPicturePath);
        return ResultEntity;
    }

    @ResponseBody
    @RequestMapping("/upload/detail/picture")
    public ResultEntity<String> uploadDetailPicture(HttpSession session, @RequestParam("detailPicture") List<MultipartFile> detailPictureList) throws IOException {
        //验证是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(obj==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken = memberSignSuccessVO.getToken();

        //验证集合是否为空
        if(CrowdUtils.collectionEffectiveCheck(detailPictureList)==false){
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        //实现文件上传
        //保存详情图片上传完成后的路径
        List<String> detailPicturePathList=new ArrayList<>();
        for(MultipartFile multipartFile : detailPictureList){
            boolean empty = multipartFile.isEmpty();
            if(empty){
                continue;
            }
            //文件上传
            String originalFilename = multipartFile.getOriginalFilename();
            String fileName = UploadUtil.generateFileName(originalFilename);
            InputStream inputStream = multipartFile.getInputStream();
            UploadUtil.uploadSingleFile(endpint,accessKeyId,accessKeySecret,fileName,detailPictureFolderName,bucketName,inputStream);
            String detailPicturePath = domain+"/"+detailPictureFolderName+"/"+fileName;
            detailPicturePathList.add(detailPicturePath);
        }
        //保存到projectVO
        Object obj2 = session.getAttribute(CrowdConstant.ATTT_NAME_INITER_PROJECT);
        if(obj2==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITER_PROJECT);
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken = projectVO.getProjectTempToken();

        ResultEntity<String> resultEntity = projectManagerRemoteService.saveDetailPicturePathList(memberSignToken, projectTempToken, detailPicturePathList);
        return resultEntity;
    }

    @RequestMapping("/save/project/information")
    @ResponseBody
    public ResultEntity<String> saveProjectinformation(ProjectVO projectVO,HttpSession session){
        //登录检查
        MemberSignSuccessVO signSuccessVO = (MemberSignSuccessVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(signSuccessVO==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        String token = signSuccessVO.getToken();
        projectVO.setMemberSignToken(token);
        //获取projectToken
        Object obj = session.getAttribute(CrowdConstant.ATTT_NAME_INITER_PROJECT);
        if (obj==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITER_PROJECT);
        }
        ProjectVO project=(ProjectVO)obj;
        projectVO.setProjectTempToken(project.getProjectTempToken());


        ResultEntity<String> stringResultEntity = projectManagerRemoteService.saveProjectInformation(projectVO);
        return stringResultEntity;
    }

    @RequestMapping("/to/project/return")
    public String toProjectReturn(){
        return "start-step-2";
    }

    @RequestMapping("/save/return/vo")
    public String saveReturnVO(ReturnVO returnVO,
                               @RequestParam("describPic") MultipartFile descriPic,
                               Model model,
                               HttpSession session) throws IOException {
        //验证是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(obj==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken = memberSignSuccessVO.getToken();

        Object obj2 = session.getAttribute(CrowdConstant.ATTT_NAME_INITER_PROJECT);
        if(obj2==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"请同意协议");
            return "start";
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken = projectVO.getProjectTempToken();

        //文件上传
        //验证是否选择文件
        if(descriPic==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_NO_FILE);
            return "start-step-2.html";
        }
        //获取旧文件名，生成新文件名
        String originalFilename = descriPic.getOriginalFilename();
        String fileName = UploadUtil.generateFileName(originalFilename);
        //把文件对象转成文件流
        InputStream inputStream = descriPic.getInputStream();
        //文件上传
        UploadUtil.uploadSingleFile(endpint,accessKeyId,accessKeySecret,fileName,returnFolderName,bucketName,inputStream);
        returnVO.setDescribPicPath(domain+"/"+returnFolderName+"/"+fileName);
        //保存returnVo
        returnVO.setMemberSignToken(memberSignToken);
        returnVO.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveReturnVO(returnVO);
        if(resultEntity.getResult().equals(resultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity.getMessage());
            return "start-step-2.html";
        }
        return "start-step-3.html";
    }

    @RequestMapping("/save/member/confirm/info/vo")
    public String saveMemberConfirmInfoVO(MemberConfirmInfoVO vo, HttpSession session,Model model){
        System.out.println("进saveMemberConfirmInfoVO方法啦");
        //验证是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(obj==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken = memberSignSuccessVO.getToken();

        Object obj2 = session.getAttribute(CrowdConstant.ATTT_NAME_INITER_PROJECT);
        if(obj2==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"请同意协议");
            return "start";
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        vo.setMemberSignToken(memberSignToken);
        vo.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveMemberConfirmInfoVO(vo);
        if(resultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity.getMessage());
            return "start-step-3";
        }
        //保存数据库
        ResultEntity<String> databaseResultEntity = projectManagerRemoteService.saveWholeProject(memberSignToken, projectTempToken);
        if(databaseResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,databaseResultEntity.getMessage());
            return "start-step-3";
        }
        return "start-step-4";

    }

}
